package com.yitao.cms.service.product;

import com.skipper.base.service.GenericEntityService;
import com.yitao.client.constant.ProductConstant;
import com.yitao.client.dto.product.ProductStockDto;
import com.yitao.client.model.product.ProductStockModel;
import com.yitao.client.model.product.QProductStockModel;
import com.yitao.cms.utils.BaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductCmsStockService extends GenericEntityService<ProductStockModel, ProductStockDto, QProductStockModel> {

    public ProductCmsStockService(EntityManager entityManager) {
        super(entityManager);
    }

    private BaseUtils base = BaseUtils.getInstance();
    @Autowired
    private ProductCmsSkuService productCmsSkuService;

    /**
     * 新增
     *
     * @param productStockModel
     * @return
     */
    @Transactional
    public ProductStockModel save(ProductStockModel productStockModel) {
        try {
            ProductStockModel productStockModel1 = repository.save(productStockModel);
            return productStockModel1;
        } catch (Exception e) {
            logger.error("新增数据异常{}", e.getMessage());
            return null;
        }
    }

    @Transactional
    public int updateProductStockStatus(Long productId, ProductConstant.ProductEnableEnum productEnableEnum) {
        return repository.updateByWhere(Q.productId.eq(productId), it -> it.set(Q.isEnable, productEnableEnum.getCode()));
    }


    /**
     * 根据skuId查询数据返回第一条
     *
     * @param skuId
     * @return
     */
    public ProductStockDto findProductStockBySkuId(Long skuId) {
        if (skuId != null) {
            List<ProductStockDto> productStockDtoList = repository.findAll(Q.skuId.eq(skuId)).stream().map(this::convertEntityToDto).collect(Collectors.toList());
            if (productStockDtoList != null && productStockDtoList.size() > 0) {
                return productStockDtoList.get(0);
            }
        }
        return null;
    }

    /**
     * 根据ID修改数据
     *
     * @param request
     * @param stockId
     * @param salesPrice
     * @param stock
     * @return
     */
   /* @Transactional
    public DataOutput updateProductStockById(HttpServletRequest request, Long stockId, Long salesPrice, Integer stock) {
        try {
            //判断参数
            if (stockId == null || salesPrice == null || stock == null) {
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), CommonStatus.BAD_REQUEST.getMessage());
            }
            OperationUserCmsModel userSession = UserSession.getUserSession(request);
            if (userSession == null) {
                return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
            }
            ProductStockModel productStockModel1 = queryFactory.select(Q).from(Q).where(Q.id.eq(stockId)).fetchOne();
            if (productStockModel1 != null) {
                productStockModel1.setLastUpdateBy(userSession.getId());
                productStockModel1.setLastUpdateTime(new Date());
                productStockModel1.setEntityStock(stock);
                repository.save(productStockModel1);
            }
            if (productStockModel1 != null) {
                ProductStockModel productStockModel = repository.findOne(Q.id.eq(stockId));
                if (productStockModel != null) {
                    return productCmsSkuService.updateProductSalesAndStockById(productStockModel.getSkuId(), salesPrice, stock);
                }
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "请确定库存表stockId数据是否存在!");
            } else {
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "修改失败，请确定stockId数据是否存在!");
            }
        } catch (Exception e) {
            logger.error("修改库存数据失败{}", e.getMessage());
            return new DataOutput(CommonStatus.SERVER_ERROR.getCode(), e.getMessage());
        }
    }*/


    /**
     * 批量修改售价及库存
     *
     * @param request
     * @param productId
     * @param salesPrice
     * @param stock
     * @return
     */
   /* @Transactional
    public DataOutput updateProductStockByProductId(HttpServletRequest request, Long productId, Long salesPrice, Integer stock) {
        try {
            //判断参数
            if (productId == null || salesPrice == null || stock == null) {
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "参数不能为空!");
            }
            OperationUserCmsModel userSession = UserSession.getUserSession(request);
            if (userSession == null) {
                return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
            }

            int result = repository.updateByWhere(Q.productId.eq(productId), it -> it.
                    set(Q.entityStock, stock)
                    .set(Q.lastUpdateBy, Long.valueOf(userSession.getId()))
                    .set(Q.lastUpdateTime, base.getNow())
            );
            if (result > 0) {
                return productCmsSkuService.updateProductSalesAndStockByProductId(productId, salesPrice, stock);
            } else {
                return new DataOutput(CommonStatus.SERVER_ERROR.getCode(), "请确定规格信息是否存在");
            }
        } catch (Exception e) {
            logger.error("修改库存数据失败{}", e.getMessage());
            return new DataOutput(CommonStatus.SERVER_ERROR, e.getMessage());
        }
    }*/

}
